package co.yixiang.yshop.module.product.service.storeproductcateref;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import co.yixiang.yshop.module.product.dal.dataobject.storeproductcateref.StoreProductCategoryRefDO;
import co.yixiang.yshop.module.product.dal.mysql.storeproductcateref.StoreProductCategoryRefMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author pepis
 * @apiNote
 **/
@Service
@Slf4j
public class StoreProductCategoryRefServiceImpl extends ServiceImpl<StoreProductCategoryRefMapper, StoreProductCategoryRefDO> implements StoreProductCategoryRefService {
    @Resource
    private StoreProductCategoryRefMapper mapper;

    @Override
    public void saveProductCategoryRef(List<Long> cateIdList, Long productId, boolean isAdd) {
        if(!isAdd){
            mapper.delete(Wrappers.lambdaQuery(StoreProductCategoryRefDO.class).eq(StoreProductCategoryRefDO::getProductId,productId));
        }
        if(ObjectUtil.isNotEmpty(cateIdList)){
            List<StoreProductCategoryRefDO> collect = cateIdList.stream().map(item -> {
                StoreProductCategoryRefDO refDO = new StoreProductCategoryRefDO();
                refDO.setCateId(item);
                refDO.setProductId(productId);
                return refDO;
            }).collect(Collectors.toList());
            mapper.insertBatch(collect);
        }
    }

    @Override
    public List<Long> getProductIdListByCateId(List<Long> cateIdList) {
        if(ObjectUtil.isEmpty(cateIdList)){
            return ListUtil.empty();
        }
        List<StoreProductCategoryRefDO> list = mapper.selectList(Wrappers.lambdaQuery(StoreProductCategoryRefDO.class)
                .in(StoreProductCategoryRefDO::getCateId, cateIdList)
                .select(StoreProductCategoryRefDO::getProductId)
        );
        List<Long> productIdList = list.stream().map(StoreProductCategoryRefDO::getProductId).distinct().collect(Collectors.toList());
        return productIdList;
    }

    @Override
    public List<Long> getCateIdListByProductId(Long productId) {
        List<StoreProductCategoryRefDO> list = mapper.selectList(Wrappers.lambdaQuery(StoreProductCategoryRefDO.class)
                .in(StoreProductCategoryRefDO::getProductId, productId)
                .select(StoreProductCategoryRefDO::getCateId)
        );
        return list.stream().map(StoreProductCategoryRefDO::getCateId).distinct().collect(Collectors.toList());
    }
}
